/*
 * @lc app=leetcode.cn id=113 lang=cpp
 *
 * [113] 路径总和 II
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution
{
public:
    vector<vector<int>> res;
    vector<int> path;
    void traversal(TreeNode *node, int targetSum)
    {
        if (!node->left && !node->right)
        {
            if (targetSum == 0)
            {
                res.push_back(path);
            }
            return;
        }
        if (node->left)
        {
            path.push_back(node->left->val);
            targetSum = targetSum - node->left->val;
            traversal(node->left, targetSum);
            targetSum = targetSum + node->left->val;
            path.pop_back();
        }
        if (node->right)
        {
            path.push_back(node->right->val);
            targetSum = targetSum - node->right->val;
            traversal(node->right, targetSum);
            targetSum = targetSum + node->right->val;
            path.pop_back();
        }
        return;
    }
    vector<vector<int>> pathSum(TreeNode *root, int targetSum)
    {
        if (root == NULL)
        {
            return res;
        }
        path.push_back(root->val);
        traversal(root, targetSum - root->val);
        return res;
    }
};
// @lc code=end

